﻿using System;
using System.Web.UI.WebControls;
using ResearchRepository.Models;

namespace ResearchRepository
{
    public partial class RRAccount : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // if not logged in, then redirect to login page
            if (Session[GLOBALS.userObjSessionVar] == null)
            {
                Response.Redirect("Login.aspx");
            }
            //TODO??
        }

        //when change email is checked, enable email textboxes
        //when unchecked, disable textboxes
        protected void OnCheckedEmail(object sender, EventArgs e)
        {
            if (!ChangeEmail.Checked)
            {
                NewEmail.Text = "";
                NewEmailConfirm.Text = "";
            }
            else
            {
                RRUser user = (RRUser)Session[GLOBALS.userObjSessionVar];
                NewEmail.Text = user.UserName;
                NewEmailConfirm.Text = user.UserName;
            }

            NewEmail.Enabled = ChangeEmail.Checked;
            NewEmailConfirm.Enabled = ChangeEmail.Checked;
            ChangeAccountSubmit.Enabled = ChangeEmail.Checked || ChangePassword.Checked || ChangeName.Checked || ChangeUniversityOrDept.Checked;
        }

        //when change password is checked, enable password textboxes
        //when unchecked, disable textboxes
        protected void OnCheckedPassword(object sender, EventArgs e)
        {
            if (!ChangePassword.Checked)
            {
                NewPassword.Text = "";
                NewPasswordConfirm.Text = "";
            }

            NewPassword.Enabled = ChangePassword.Checked;
            NewPasswordConfirm.Enabled = ChangePassword.Checked;
            ChangeAccountSubmit.Enabled = ChangeEmail.Checked || ChangePassword.Checked || ChangeName.Checked || ChangeUniversityOrDept.Checked;
        }

        //when change name is checked, enable name textboxes and prepopulate
        //with current user's info
        //when unchecked, disable textboxes
        protected void OnCheckedChangeName(object sender, EventArgs e)
        {
            PrefixTitles.Enabled = ChangeName.Checked;
            FirstName.Enabled = ChangeName.Checked;
            MiddleName.Enabled = ChangeName.Checked;
            LastName.Enabled = ChangeName.Checked;
            PostfixTitles.Enabled = ChangeName.Checked;

            if (ChangeName.Checked)
            {
                RRUser user = (RRUser)Session[GLOBALS.userObjSessionVar];
                PrefixTitles.Text = user.PreTitles;
                FirstName.Text = user.FirstName;
                MiddleName.Text = user.MiddleName;
                LastName.Text = user.LastName;
                PostfixTitles.Text = user.PostTitles;
            }
            else
            {
                PrefixTitles.Text = "";
                FirstName.Text = "";
                MiddleName.Text = "";
                LastName.Text = "";
                PostfixTitles.Text = "";
            }

            ChangeAccountSubmit.Enabled = ChangeEmail.Checked || ChangePassword.Checked || ChangeName.Checked || ChangeUniversityOrDept.Checked;
        }

        //when change university/dept is checked, enable radio buttons for all choices
        //default to known university/known dept where current user's info is selected if belonging to 
        //a university/dept
        protected void OnCheckedChangeUniversityOrDept(object sender, EventArgs e)
        {
			// reinitialize or disable, depending on new state
			NoUniversity.Enabled = ChangeUniversityOrDept.Checked;
			KnownUniversity.Enabled = ChangeUniversityOrDept.Checked;
			NewUniversity.Enabled = ChangeUniversityOrDept.Checked;
			NoUniversity.Checked = false;
			KnownUniversity.Checked = false;
			NewUniversity.Checked = false;
			NoDepartment.Enabled = ChangeUniversityOrDept.Checked;
			NoDepartment.Checked = false;
			KnownDepartment.Checked = false;
			NewDepartment.Checked = false;

			//
			// if unchecked, then disable all university and department options and inputs
			if (!ChangeUniversityOrDept.Checked)
			{
				KnownUniversityList.Enabled = false;//ChangeUniversityOrDept.Checked;
				NewUniversityTextbox.Enabled = false;//ChangeUniversityOrDept.Checked;

				KnownDepartment.Enabled = false;//ChangeUniversityOrDept.Checked;
				KnownDepartmentList.Enabled = false;//ChangeUniversityOrDept.Checked;
				NewDepartment.Enabled = false;//ChangeUniversityOrDept.Checked;
				NewDepartmentTextbox.Enabled = false;//ChangeUniversityOrDept.Checked;
			}
			else	// reinitialize with current info
			{
				RRUser u = (RRUser) Session[GLOBALS.userObjSessionVar];
				// if no university currently selected
				if (u.UnivID == 0)
				{
					NoUniversity.Checked = true;
					OnCheckedNoUniversity(sender, e);
				}
				else	// set current university
				{
					KnownUniversity.Checked = true;
					OnCheckedKnownUniversity(sender, e);										// populate university list
					KnownUniversityList.Items.FindByValue(u.UnivID.ToString()).Selected = true;	// select current university
					// if no department currently selected
					if (u.DeptID == 0)
					{
						NoDepartment.Checked = true;
						OnCheckedNoDepartment(sender, e);
					}
					else	// set current department
					{
						KnownDepartment.Checked = true;
						OnCheckedKnownDepartment(sender, e);										// populate department list
						KnownDepartmentList.Items.FindByValue(u.DeptID.ToString()).Selected = true;	// select current department
					}
				}
			}
            ChangeAccountSubmit.Enabled = ChangeEmail.Checked || ChangePassword.Checked || ChangeName.Checked || ChangeUniversityOrDept.Checked;
        }

        //when no university is selected, only dept option enabled should be No Department
        protected void OnCheckedNoUniversity(object sender, EventArgs e)
        {
			// disable all university inputs
			KnownUniversityList.Enabled = false;
            NewUniversityTextbox.Enabled = false;

			// disable department options and inputs
			NoDepartment.Checked = true;
			KnownDepartment.Checked = false;
			NewDepartment.Checked = false;
			OnCheckedNoDepartment(sender, e);
			KnownDepartment.Enabled = false;
			NewDepartment.Enabled = false;
        }

        //when known university is selected, populate dropdownlist with existing universities
        //and enable all dept options
        protected void OnCheckedKnownUniversity(object sender, EventArgs e)
        {
			// enable/disable university inputs appropriately
            KnownUniversityList.Enabled = true;
            NewUniversityTextbox.Enabled = false;

			// enable department options
            KnownDepartment.Enabled = true;
			NewDepartment.Enabled = true;
			// NewDepartmentTextbox does not change 'Enabled' state

			// populate university list
            var universities = RRDatabaseManager.getUniversityList();
            KnownUniversityList.DataSource = universities;
            KnownUniversityList.DataTextField = "UnivName";
            KnownUniversityList.DataValueField = "UnivId";
            KnownUniversityList.DataBind();
        }

        //when new university is selected, enable its textbox and known dept should be disable dept option
        protected void OnCheckedNewUniversity(object sender, EventArgs e)
        {
			// enable/disable university inputs
			KnownUniversityList.Enabled = false;
            NewUniversityTextbox.Enabled = true;

			// disable/enable department options appropriately
			KnownDepartment.Enabled = false;
			NewDepartment.Enabled = true;
			
			// disable/enable department inputs appropriately
			KnownDepartmentList.Enabled = false;
			if (KnownDepartment.Checked)
			{
				NoDepartment.Checked = true;
				KnownDepartment.Checked = false;
				NewDepartment.Checked = false;
				NewDepartmentTextbox.Enabled = false;
			}
        }

        protected void OnSelectedUniversityChanged(object sender, EventArgs e)
        {
			// if KnownDepartment is selected, then re-populate known department list
			if (KnownDepartment.Checked)
			{
				OnCheckedKnownDepartment(sender, e);
			}
        }

        //when no department is selected, only dept option enabled should be No Department
        protected void OnCheckedNoDepartment(object sender, EventArgs e)
        {
			// disable department inputs
            KnownDepartmentList.Enabled = false;
			NewDepartmentTextbox.Enabled = false;
        }

        //when known dept is selected, populate dropdownlist with existing depts for selected university
        //known dept should only be able to be selected when known university is selected
        protected void OnCheckedKnownDepartment(object sender, EventArgs e)
        {
			// enable/disable department inputs appropriately
            KnownDepartmentList.Enabled = true;
			NewDepartmentTextbox.Enabled = false;

			// re-populate known department list
            var departments = RRDatabaseManager.getDepartmentList(int.Parse(KnownUniversityList.SelectedValue));
            KnownDepartmentList.DataSource = departments;
            KnownDepartmentList.DataTextField = "DeptName";
            KnownDepartmentList.DataValueField = "DeptId";
            KnownDepartmentList.DataBind();
        }

        //when new dept is selected, enable its textbox
        protected void OnCheckedNewDepartment(object sender, EventArgs e)
        {
			// enable/disable department inputs appropriately
            KnownDepartmentList.Enabled = false;
			NewDepartmentTextbox.Enabled = true;
        }

        protected void ChangeAccountCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("Browse.aspx");
        }

        protected void ChangeAccountSubmit_Click(object sender, EventArgs e)
        {
            RRUser user = (RRUser)Session[GLOBALS.userObjSessionVar];

            string university = "";
            string dept = "";

            //get values for changes in university/dept, NULL for no university/dept
            if (ChangeUniversityOrDept.Checked)
            {
                if (NoUniversity.Checked)
                    university = "NULL";
                else if (KnownUniversity.Checked)
                    university = KnownUniversityList.SelectedValue;
                else if (NewUniversity.Checked)
                    university = NewUniversityTextbox.Text;
                if (NoDepartment.Checked)
                    dept = "NULL";
                else if (KnownDepartment.Checked)
                    dept = KnownUniversityList.SelectedValue;
                else if (NewDepartment.Checked)
                    dept = NewDepartmentTextbox.Text;
            }
	//TODO: allow partial update
	//TODO: allow selection of university without department (ie: find dummy department for selected university)
            //only update user into if neither new university nor new department is checked
            if (ChangeEmail.Checked || ChangePassword.Checked || ChangeName.Checked || (ChangeUniversityOrDept.Checked && (!NewUniversity.Checked && !NewDepartment.Checked)))
            {
                RRDatabaseManager.updateAccountInfo(user.UserID, NewEmailConfirm.Text, NewPasswordConfirm.Text,
                                                    PrefixTitles.Text, FirstName.Text, MiddleName.Text, LastName.Text,
                                                    PostfixTitles.Text, dept);
            }

            bool submitReqSuccess = false;
            //if new university/new department, generate new RRRequest
            if (NewUniversity.Checked && !(String.IsNullOrEmpty(university)))
            {
                RRRequest req = new RRRequest();
                req.ReqType = RRRequestType.NewUnivOrDept;
                req.UserID = user.UserID;
                req.NewUnivName = university;
                req.NewDeptName = dept;
                try
                {
                    RRDatabaseManager.createRequest(req);
                    successDiv.Visible = true;
                }
                catch (Exception x)
                {
                    //TODO?? handle?
                    failureDiv.Visible = true;
                }
            }
        }
    }
}